// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/common/memory/scratch.h>

#include <gtest/gtest.h>

using namespace kumo::pollux;

TEST(ScratchTest, basic) {
  Scratch scratch;
  {
    ScratchPtr<int32_t> ints(scratch);
    ScratchPtr<int64_t> longs(scratch);
    auto tempInts = ints.get(1000);
    auto tempLongs = longs.get(2000);
    std::fill(tempInts, tempInts + 1000, -1);
    std::fill(tempLongs, tempLongs + 2000, -1);
    EXPECT_EQ(0, scratch.retained_size());
  }
  EXPECT_EQ(20352, scratch.retained_size());
  {
    ScratchPtr<int32_t> ints(scratch);
    ScratchPtr<int64_t> longs(scratch);
    longs.get(2000);
    auto tempInts = ints.get(1000);
    std::fill(tempInts, tempInts + 1000, -1);
    std::fill(tempInts, tempInts + 2000, -1);
    EXPECT_EQ(0, scratch.retained_size());
  }
  // The scratch vectors were acquired in a different order, so the smaller got
  // resized to the larger size.
  EXPECT_EQ(32640, scratch.retained_size());
  scratch.trim();
  EXPECT_EQ(0, scratch.retained_size());
  {
    ScratchPtr<int32_t, 10> ints(scratch);
    // The size is the inline size, nothing gets returned to 'scratch'.
    auto temp = ints.get(10);
    temp[0] = 1;
  }
  EXPECT_EQ(0, scratch.retained_size());
}

TEST(ScratchTest, large) {
  constexpr int32_t kSize = 100;
  Scratch scratch;
  std::vector<std::unique_ptr<ScratchPtr<int32_t>>> pointers;
  for (auto i = 0; i < kSize; ++i) {
    pointers.push_back(std::make_unique<ScratchPtr<int32_t>>(scratch));
    pointers.back()->get(1000);
  }
  pointers.clear();
  // 100 times 1000 bytes returned.
  EXPECT_LT(100'000, scratch.retained_size());
  for (auto i = 0; i < kSize; ++i) {
    pointers.push_back(std::make_unique<ScratchPtr<int32_t>>(scratch));
    pointers.back()->get(1000);
  }
  EXPECT_EQ(0, scratch.retained_size());
}
